<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2017/3/28 20:56
 * @copyright   WuHan HuQi Technology Co.,Ltd.
 * @url         http://cnhuqi.com
 */

class Ticket_Model extends WX_Model
{
    /**
     * init
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取列表
     * @param int $offset
     * @param int $limit
     * @return array
     */
    public function getLists($offset = 0, $limit = 20)
    {
        $db = clone($this->db);
        $where = [
            'status >=' => 0
        ];

        $total = $db->where($where)->count_all_results('promoter_ticket');

        if ($total <= 0) {
            return [
                'total' => 0,
                'data' => []
            ];
        }
        $db->limit($limit, $offset);
        $db->order_by("id desc");
        $query = $db->get_where('promoter_ticket', $where);

        $res = $query->result_array();

        foreach ($res as &$row) {
            $row['time_start'] = date('Y-m-d', strtotime($row['time_start']));
            $row['time_end'] = date('Y-m-d', strtotime($row['time_end']));
            $row['amount'] = money_format('%i', $row['amount'] / 100);
            $row['limit_amount'] = money_format('%i', $row['limit_amount'] / 100);
        }

        return [
            'total' => $total,
            'data' => $res
        ];
    }

    /**
     * @param $userid
     * @param $type
     * @param int $offset
     * @param int $limit
     * @return mixed
     */
    public function getTicketsList($userid, $type, $offset = 0, $limit = 20)
    {
        $type = "_" . $type;
        return $this->$type($userid, $offset, $limit);
    }

    public function _expires($userid, $offset, $limit)
    {
        $db = clone($this->db);
        $db->where([
            'ut.userid' => $userid,
            'ut.used' => 0,
            'pt.time_end <=' => date('Y-m-d H:i:s')
        ]);

        $db->from('user_ticket as ut');
        $db->join('promoter_ticket as pt', 'pt.id = ut.ticketid');
        $db->select('pt.*');
        $q = $db->get();
        $results = $q->result_array();
        if(!empty($results)) foreach ($results as &$result) {
            $result["amount_format"] = floor($result['amount'] / 100);
            $result["amount_cny"] = money_format('%i', $result['amount'] / 100);
            $result['limit_amount_format'] = floor($result['limit_amount'] / 100);
            $result['limit_amount_cny'] = money_format('%i', $result['limit_amount'] / 100);
            $result['time_start'] = date("Y.m.d", strtotime($result['time_start']));
            $result['time_end'] = date("Y.m.d", strtotime($result['time_end']));
        }
        return $results;
    }

    /**
     * @param $userid
     * @param $offset
     * @param $limit
     * @return array
     */
    public function _used($userid, $offset, $limit)
    {
        // 1. 先查找未领取的券
        $userTicketDb = clone($this->db);
        $userTicketDb->select("ticketid");
        $q = $userTicketDb->get_where('user_ticket', [
            'userid' => $userid,
            'used' => 1
        ]);
        $rows = $q->result_array();
        $ids = [];
        if ($rows) foreach($rows as $row) {
            $ids[] = $row['ticketid'];
        }

        if (empty($ids)) {
            return [];
        }

        $ticketDb = clone($this->db);
        $ticketDb->where_in("id", $ids);
        $query = $ticketDb->get("promoter_ticket");

        $results = $query->result_array();
        if (!empty($results)) foreach ($results as &$result) {
            $result["amount_format"] = floor($result['amount'] / 100);
            $result["amount_cny"] = money_format('%i', $result['amount'] / 100);
            $result['limit_amount_format'] = floor($result['limit_amount'] / 100);
            $result['limit_amount_cny'] = money_format('%i', $result['limit_amount'] / 100);
            $result['time_start'] = date("Y.m.d", strtotime($result['time_start']));
            $result['time_end'] = date("Y.m.d", strtotime($result['time_end']));
        }
        return $results;
    }

    public function _nouse($userid, $offset, $limit)
    {
        // 1. 先查找未领取的券
        $userTicketDb = clone($this->db);
        $userTicketDb->select("ticketid");
        $q = $userTicketDb->get_where('user_ticket', [
            'userid' => $userid,
            'used' => 0,
        ]);
        $rows = $q->result_array();
        $ids = [];
        if ($rows) foreach($rows as $row) {
            $ids[] = $row['ticketid'];
        }

        if (empty($ids)) {
            return [];
        }

        $ticketDb = clone($this->db);
        $ticketDb->where_in("id", $ids);
        $ticketDb->where('time_end >=', date('Y-m-d H:i:s'));
        $query = $ticketDb->get("promoter_ticket");

        $results = $query->result_array();
        if (!empty($results)) foreach ($results as &$result) {
            $result["amount_format"] = floor($result['amount'] / 100);
            $result["amount_cny"] = money_format('%i', $result['amount'] / 100);
            $result['limit_amount_format'] = floor($result['limit_amount'] / 100);
            $result['limit_amount_cny'] = money_format('%i', $result['limit_amount'] / 100);
            $result['time_start'] = date("Y.m.d", strtotime($result['time_start']));
            $result['time_end'] = date("Y.m.d", strtotime($result['time_end']));
        }
        return $results;
    }

    /**
     * 未领取的优惠券
     * @param $userid
     * @param int $offset
     * @param int $limit
     * @return mixed
     */
    public function _noget($userid, $offset = 0, $limit = 20)
    {
        // 1. 先超找已经领取的券
        $userTicketDb = clone($this->db);
        $userTicketDb->select("ticketid");
        $q = $userTicketDb->get_where('user_ticket', ['userid' => $userid]);
        $rows = $q->result_array();
        $ids = [];
        if ($rows) foreach($rows as $row) {
            $ids[] = $row['ticketid'];
        }

        $ticketDb = clone($this->db);

        if (!empty($ids)) {
            $sql = "SELECT * FROM promoter_ticket WHERE id NOT IN ? AND wechat = 1 AND time_end > ? AND `gets` < `num` ORDER BY id DESC LIMIT ?, ?";
            $query = $ticketDb->query($sql, array($ids, date("Y-m-d H:i:s"), $offset, $limit));
        } else {
            $sql = "SELECT * FROM promoter_ticket WHERE wechat = 1 AND time_end > ? AND `gets` < `num` ORDER BY id DESC LIMIT ?, ?";
            $query = $ticketDb->query($sql, array(date("Y-m-d H:i:s"), $offset, $limit));
        }

        $results = $query->result_array();
        if (!empty($results)) foreach ($results as &$result) {
            $result["amount_format"] = floor($result['amount'] / 100);
            $result["amount_cny"] = money_format('%i', $result['amount'] / 100);
            $result['limit_amount_format'] = floor($result['limit_amount'] / 100);
            $result['limit_amount_cny'] = money_format('%i', $result['limit_amount'] / 100);
            $result['time_start'] = date("Y.m.d", strtotime($result['time_start']));
            $result['time_end'] = date("Y.m.d", strtotime($result['time_end']));
        }
        return $results;
    }

    /**
     * 概览
     * @param $userid
     * @return array
     */
    public function getSummary($userid)
    {
        return [
            'nouse' => $this->_getNoUse($userid),
            'used' => $this->_getUsed($userid),
            'expires' => $this->_getExpires($userid),
            'noget' => $this->_getNoGet($userid)
        ];
    }

    /**
     * 未领取的
     * @param $userid
     * @return mixed
     */
    private function _getNoGet($userid)
    {
        $userTicketDb = clone($this->db);
        $userTicketDb->select("ticketid");
        $q = $userTicketDb->get_where('user_ticket', ['userid' => $userid]);
        $rows = $q->result_array();
        $ids = [];
        if ($rows) foreach($rows as $row) {
            $ids[] = $row['ticketid'];
        }

        $ticketDb = clone($this->db);

        if (!empty($ids)) {
            $sql = "SELECT count(id) as c FROM promoter_ticket WHERE id NOT IN ? AND wechat = 1 AND time_end > ? AND `gets` < `num` ORDER BY id DESC LIMIT 1";
            $query = $ticketDb->query($sql, array($ids, date("Y-m-d H:i:s")));
        } else {
            $sql = "SELECT count(id) as c FROM promoter_ticket WHERE wechat = 1 AND time_end > ? AND `gets` < `num` ORDER BY id DESC LIMIT 1";
            $query = $ticketDb->query($sql, array(date("Y-m-d H:i:s")));
        }

        $results = $query->row_array();
        return $results['c'];
    }

    /**
     * 过期
     * @param $userid
     * @return mixed
     */
    private function _getExpires($userid)
    {
        $db = clone($this->db);
        $db->where([
            'ut.userid' => $userid,
            'ut.used' => 0,
            'pt.time_end <=' => date('Y-m-d H:i:s')
        ]);

        $db->from('user_ticket as ut');
        $db->join('promoter_ticket as pt', 'pt.id = ut.ticketid');

        return $db->count_all_results();
    }

    /**
     * 已使用
     * @param $userid
     * @return mixed
     */
    private function _getUsed($userid)
    {
        $db = clone($this->db);
        $db->where([
            'userid' => $userid,
            'used' => 1
        ]);

        return $db->count_all_results('user_ticket');
    }

    private function _getNoUse($userid)
    {
        $db = clone($this->db);
        $db->where([
            'ut.userid' => $userid,
            'ut.used' => 0,
            'pt.time_end >=' => date('Y-m-d H:i:s')
        ]);

        $db->from('user_ticket as ut');
        $db->join('promoter_ticket as pt', 'pt.id = ut.ticketid');

        return $db->count_all_results();
    }

    /**
     * 用户领取票券
     * @param $userid
     * @param $id
     * @return bool
     */
    public function getTicket($userid, $id)
    {
        $db = clone($this->db);
        $db->trans_start();

        $query = $db->get_where('promoter_ticket', ['id' => $id]);
        $row = $query->row_array();

        if (!$row) {
            return false;
        }

        if ($row['num'] <= $row['gets']) {
            return false;
        }

        $db->set('gets', 'gets+1', false);
        $db->where('id', $id);
        $db->update('promoter_ticket');
        $affected = $db->affected_rows();

        // save to user_ticket
        $uDb = clone($this->db);
        $insertid = $uDb->insert('user_ticket', [
            'userid' => $userid,
            'ticketid' => $id,
        ]);

        if ($affected && $insertid) {
            $db->trans_complete();
        }

        return $db->trans_status();
    }

    /**
     * 获取ticket
     * @param int $ticketID
     * @return mixed
     */
    public function getTicketById($ticketID = 0)
    {
        $db = clone($this->db);
        $q = $db->get_where('promoter_ticket', ['id'=> $ticketID]);
        return $q->row_array();
    }

    /**
     * @param $userid
     * @param $ticketid
     */
    public function getTicketForUser($userid, $ticketid)
    {
        $db = clone($this->db);
        $q = $db->get_where('user_ticket', ['userid' => $userid, 'id' => $ticketid]);
        return $q->row_array();
    }

    /**
     * 获取用户持有优惠券数量
     * @param $userid
     * @return mixed
     */
    public function getTicketSummaryForUser($userid)
    {
        $db = clone($this->db);
        $db->where(['userid' => $userid, 'used' => 0]);
        return $db->count_all_results('user_ticket');
    }
}
